import { uPlc, get_umt, is_empty, to_float, loc, obj_str, uDb, d_sort, uReal, cline, for_obj } from 'sui';
import { User } from 'cache';

const reload = (hDone, setMain, mod="pair") => {
    uReal(hDone, "pair/load",
        {
            line: cline(),
            k: mod,
        },
        r => {
            const ret = [];

            for_obj(r, (tsn, pair) => {
                let tmp = [];

                for_obj(pair, (k, v) => tmp.push(v));

                ret.push({
                    sn: tsn,
                    pnum: tmp.length,
                    sub: tmp,
                });
            });

            d_sort(ret, "sn");
            ret.forEach((d, i) => d["index"] = i + 1);

            setMain(ret);
        }, e => setMain(null));
};

const load_tech = (setList) => {
    uDb(null, "tech/list", { line: cline() },
        r => {
            const ctl = [];

            r.forEach(d => {
                const mt = obj_str(d, "mt");
                let name = "";
                if (mt === "T") {
                    name = loc("l_713");
                } else if (mt === "G") {
                    name = loc("l_712");
                }

                if (!name) {
                    return;
                }

                ctl.push({
                    sn: obj_str(d, "sn"),
                    name: name,
                    val: obj_str(d, "ball"),
                    mt: mt,
                    num: obj_str(d, "num"),
                });
            });

            setList(ctl);
        },
        e => {
            setList(null);
        });
};

// mod: cera, stell
const load_mt = (mod, setList) => {
    uDb(null, `${mod}/list`, { line: cline() },
        r => {
            const ctl = [];

            r.forEach(d => {
                const std = to_float(obj_str(d, "std"));
                const sub = to_float(obj_str(d, "sub"));

                const name = mod === "cera" ? std + sub : sub;

                ctl.push({
                    sn: obj_str(d, "sn"),
                    name: name,
                    std: std,
                    sub: sub,
                    ball: obj_str(d, "ball"),
                });
            });

            setList(ctl);
        },
        e => setList(null));
};

const reload_auto = (hDone, form, setMain, setCk) => {
    uReal(hDone, "auto/load",
        {
            line: cline(),
        },
        v => {
            const val = {...v};
            val["mt"] = get_umt(v["mt"]);

            setMain(val);

            if (form) {
                if (v["other"]) {
                    v["ck_other"] = "Y";
                }

                form.setValue(v);
            }
        },
        e => setMain(null));
};

const save_auto = (val, hok, herr) => {
    const doSave = (data) => {
        let cmd = {};

        if (data) {
            cmd = data;
        }

        if (val) {
            for_obj(val, (k, v) => cmd[k] = v);
        }

        uDb(null, "field/md/autopair",
            {
                line: cline(),
                v: cmd,
            },
            r => hok(), e => herr());
    };

    uDb(null, "field/list/autopair",
        {
            line: cline(),
        },
        r => doSave(r), e => doSave(null));
};

const reload_group = (hDone, setMain, mod="pair") => {
    const adjust = (d, k) => {
        const v = d[k];
        if (!v) {
            return;
        }

        let tmp = Math.abs(v);
        tmp = Math.floor(tmp * 10) % 10;

        if (tmp <= 5) {
            d[k] = Math.trunc(v);
        }
        else {
            d[k] = Math.round(v);
        }
    };

    uReal(hDone, "group/load",
        {
            line: cline(),
            k: mod,
            type: "qr",
        },
        r => {
            const group = {};

            r.forEach((d, i) => {
                adjust(d, "outdia");
                adjust(d, "india");
                adjust(d, "outwidth");
                adjust(d, "standout");

                const tsn = obj_str(d, "tech");
                if (group[tsn]) {
                    group[tsn].push(d);
                } else {
                    group[tsn] = [d];
                }
            });

            const ret = [];

            for_obj(group, (k, v) => ret.push({sn: k, v: v, pnum: v.length}));

            if (mod === "pair") {
                d_sort(ret, "groupsn");
            } else {
                d_sort(ret, "sn");
            }

            ret.forEach((d, i) => d["index"] = i + 1);

            setMain(ret);
        }, e => setMain(null));
};

const filter_item = (main, data, filter) => {
    if (is_empty(main)) {
        return null;
    }

    let user = [...main];

    if (!is_empty(data)) {
        user = main.filter(d => {
            if (data.find(it => it === d)) {
                return false;
            }
            return true;
        });
    }

    if (filter) {
        user = user.filter(d => {
            const find = filter.toLowerCase();
            const tmp = d.toLowerCase();

            if (tmp.indexOf(find) >= 0) {
                return true;
            }

            return false;
        });
    }

    if (is_empty(user)) {
        return null;
    }

    return user;
};

const load_his = (setMain, fname="handcalc") => {
    const to_val = (d) => {
        const tmp = [];
        for_obj(d, (k, v) => tmp.push(v));

        return tmp.join(",");
    };

    uDb(null, `file/list/${fname}`, { line: cline() },
        r => {
            const ret = [];

            r.forEach(d => {
                const name = to_val(d);
                ret.push({ sn: obj_str(d, "sn"), name: name, v: d });
            });

            setMain(ret);
        },
        e => setMain(null));
};

const reload_mt = (hDone, setMain) => {
    reload_auto(hDone, null, v => {
        const batch = v["batch"];
        const cmd = [];

        if (batch) {
            batch.forEach(d => cmd.push(d.sn));
        }

        setMain(cmd);
    });
};

const load_try = (hDone, tp, setMain) => {
    uDb(hDone, "file/get/tryball",
        {
            line: cline(),
            sn: tp,
        },
        r => {
            const v = r.v;
            if (!v) {
                setMain(null);
                return;
            }

            v.sort();

            const ret = v.map((d, i) => {
                return {
                    index: i + 1,
                    dw: d,
                };
            });

            setMain(ret);
        },
        e => setMain(null));
};

const save_try = (hDone, tp, val, setMain) => {
    uDb(null, "file/md/tryball",
        {
            line: cline(),
            sn: tp,
            v: { v: val },
        },
        r => load_try(hDone, tp, setMain),
        e => {
            setMain(null);
            hDone();
        });
};

const get_alert = (setMain) => {
    uPlc(null, "get",
        {
            line: cline(),
            sn: "alertmsg",
        },
        r => {
            const ret = new Set();

            for_obj(r, (k, v) => {
                const tmp = k.split("#");
                if (tmp[1]) {
                    ret.add(tmp[1]);
                }
            });

            setMain(ret);
        }, e => setMain(null));
};

const get_box = (mod) => {
    const u = User.userName();
    return `${mod}${u}`;
};

export {get_box, get_alert, save_try, load_try, reload_mt, save_auto, load_his, filter_item, reload_group, reload_auto, load_mt, load_tech, reload};
